package Demo06;

import org.junit.Test;

import java.lang.reflect.Field;

public class FileDemo {
    @Test
    public void test() throws ClassNotFoundException, NoSuchFieldException {
        //获取公共的成员属性
        //1获取字节码对象
        Class<?> aClass = Class.forName("Demo06.Student");
        //2获取属性
//        Field id = aClass.getField("id");
//        System.out.println(id);
        //3获取私有的成员属性
        Field name = aClass.getDeclaredField("name");
        System.out.println(name);
    }
    //给私有属性赋值
    @Test
    public void test2() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        //给私有属性赋值
        //获取字节码对象
        Class<?> aClass = Class.forName("Demo06.Student");
        //先获取私有属性
        Field name = aClass.getDeclaredField("name") ;
        //给属性赋值 对象名称.属名性称=值
       Student o =(Student) aClass.newInstance();
       name.setAccessible(true);
        name.set(o,"李翔");
        //给sex赋值
        Field sex = aClass.getDeclaredField("sex");
        sex.setAccessible(true);
        sex.set(o,"男");
        System.out.println(o);

    }


}
